package com.example.test_witns.ui.sheets;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowInsets;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.test_witns.R;
import com.example.test_witns.pojo.TodoTask;
import com.example.test_witns.utils.MyInfosHelper;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class ModifyTaskBottomSheet extends BottomSheetDialogFragment {
    // 保持原有控件ID不变
    private EditText etTaskTitle;
    private AutoCompleteTextView actvCategory;
    private EditText etDueDate;
    private RadioGroup rgPriority;
    private EditText rgPriorityValue;
    private EditText etNotes;
    private EditText etDueTime;
    private TextView tv_title;
    private OnTaskModifiedListener onTaskModifiedListener;
    private View view;
    private TodoTask todoTask;
    private boolean isCompleted;
    private MyInfosHelper myInfosHelper;

    public ModifyTaskBottomSheet(TodoTask todoTask) {
        this.todoTask = todoTask;
    }

    public interface OnTaskModifiedListener {
        void onTaskModified(TodoTask initialTask, TodoTask modifiedTask);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        view = LayoutInflater.from(getContext()).inflate(R.layout.bottom_sheet_add_task, null);
        dialog.setContentView(view);
        myInfosHelper = new MyInfosHelper(getContext());

        isCompleted = todoTask.isCompleted();

        // 初始化视图（保持原有ID）
        tv_title = view.findViewById(R.id.tv_title);
        tv_title.setText("修改任务");
        etTaskTitle = view.findViewById(R.id.et_task_title);
        etDueDate = dialog.findViewById(R.id.et_due_date);
        actvCategory = dialog.findViewById(R.id.actv_category);
        rgPriorityValue = dialog.findViewById(R.id.rg_priority_value);
        etDueTime = dialog.findViewById(R.id.et_due_time);
        rgPriority = view.findViewById(R.id.rg_priority);
        etNotes = view.findViewById(R.id.et_notes);

        etTaskTitle.setText(todoTask.getTitle());
        etDueDate.setText(todoTask.getDueDate());
        actvCategory.setText(todoTask.getCategory());
        rgPriorityValue.setText(String.valueOf(todoTask.getPriority()));
        etDueTime.setText(todoTask.getDueTime());
        etNotes.setText(todoTask.getNotes());

        List<String> categories = Arrays.asList("工作方面", "学习", "生活", "购物");
        ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(
                getContext(),
                R.layout.item_dropdown,
                categories
        );
        actvCategory.setAdapter(categoryAdapter);
        etDueDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (etDueDate.hasFocus()){
                    Calendar calendar = Calendar.getInstance();
                    new DatePickerDialog(getContext(), (calendarView, year, month, day) -> {
                        String dateStr = String.format(Locale.getDefault(), "%04d-%02d-%02d", year, month+1, day);
                        etDueDate.setText(dateStr);
                    },
                            calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH),
                            calendar.get(Calendar.DAY_OF_MONTH))
                            .show();
                }
            }
        });
        etDueTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (etDueTime.hasFocus()){
                    showTimePickerDialog();
                }
            }
        });

        // 关闭按钮
        view.findViewById(R.id.btn_close).setOnClickListener(v -> dismiss());

        // 取消按钮
        view.findViewById(R.id.btn_cancel).setOnClickListener(v -> dismiss());

        // 确认按钮
        view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String validateInputRes = validateInput();
                if (validateInputRes.equals("OK")){
                    String setDefaultValueAndFinalCheckRes = setDefaultValueAndFinalCheck();
                    if (setDefaultValueAndFinalCheckRes.equals("OK")){
                        TodoTask modifiedTask = createTaskFromInput();
                        onTaskModifiedListener.onTaskModified(todoTask, modifiedTask);
                        dismiss();
                    }else {
                        toast_Prohibited_Style(setDefaultValueAndFinalCheckRes);
                    }
                }else {
                    toast_Prohibited_Style(validateInputRes);
                }
            }
        });

        setupCategoryDropdown();
        setupDatePicker();

        return dialog;
    }

    // 保持原有对话框逻辑不变
    private void setupCategoryDropdown() {
        // 分类下拉初始化代码...
    }

    private void setupDatePicker() {
        // 日期选择器代码...
    }

    private String validateInput() {
        if (etTaskTitle.getText().toString().isEmpty()){
            return "请输入任务标题";
        }
        if (etTaskTitle.getText().toString().length() >= 41) {
            return "标题不要超过40个字符";
        }
        if (!isValidDate(etDueDate.getText().toString()) && !etDueDate.getText().toString().isEmpty()){
            return "截止日期格式有误";
        }
        if (!isValidTime(etDueTime.getText().toString()) && !etDueTime.getText().toString().isEmpty()){
            return "截止时间格式有误";
        }
        if (etNotes.getText().toString().length() >= 801){
            return "备注不要超过800个字符";
        }
        if (actvCategory.length() >= 9){
            return "标签不要超过8个字符";
        }
        if (!rgPriorityValue.getText().toString().matches("-?\\d+") && !rgPriorityValue.getText().toString().isEmpty()) {
            return "优先级值格式有误, (1~300)";
        }
        if (rgPriorityValue.getText().toString().length() > 3){
            return "优先级值最大为300(优先级 高)";
        }
        if (!rgPriorityValue.getText().toString().isEmpty() && Integer.parseInt(rgPriorityValue.getText().toString()) > 300){
            return "优先级值最大为300(优先级 高)";
        }
        if (!rgPriorityValue.getText().toString().isEmpty() && Integer.parseInt(rgPriorityValue.getText().toString()) < 1){
            return "优先级值最小为1(优先级 低)";
        }

        return "OK";
    }

    private String setDefaultValueAndFinalCheck(){
        if (etDueDate.getText().toString().isEmpty()){
            etDueDate.setText("无时限");
        }
        if (actvCategory.length() == 0){
            actvCategory.setText("未分类");
        }
        if (etNotes.getText().toString().isEmpty()){
            etNotes.setText("无备注");
        }
        int selectedId = rgPriority.getCheckedRadioButtonId();
        RadioButton selectedRadioButton = view.findViewById(selectedId);
        if (rgPriorityValue.getText().toString().isEmpty()){
            if (selectedId != -1) {
                if (selectedRadioButton.getText().toString().equals("高优先级")){
                    String highPriority = "201";
                    rgPriorityValue.setText(highPriority);
                } else if (selectedRadioButton.getText().toString().equals("中优先级")) {
                    String mediumPriority = "101";
                    rgPriorityValue.setText(mediumPriority);
                }else {
                    String lowPriority = "1";
                    rgPriorityValue.setText(lowPriority);
                }
            }
        }
        if (Integer.parseInt(rgPriorityValue.getText().toString()) < 101 && !selectedRadioButton.getText().toString().equals("低优先级")){
            return selectedRadioButton.getText().toString() + "与值 " + rgPriorityValue.getText().toString() + "不匹配";
        }
        if (Integer.parseInt(rgPriorityValue.getText().toString()) > 100 && Integer.parseInt(rgPriorityValue.getText().toString()) < 201
                && !selectedRadioButton.getText().toString().equals("中优先级")){
            return selectedRadioButton.getText().toString() + "与值 " + rgPriorityValue.getText().toString() + "不匹配";
        }
        return "OK";
    }

    private TodoTask createTaskFromInput() {
        if (todoTask != null){
            TodoTask modifiedTask = new TodoTask(etTaskTitle.getText().toString(), actvCategory.getText().toString(),
                    Integer.parseInt(rgPriorityValue.getText().toString()),
                    etDueDate.getText().toString(), todoTask.isCompleted(), etNotes.getText().toString(),
                    LocalDateTime.now().toString(), etDueTime.getText().toString());
            modifiedTask.setId(todoTask.getId());
            return modifiedTask;
        }else {
            TodoTask modifiedTask = new TodoTask(etTaskTitle.getText().toString(), actvCategory.getText().toString(),
                    Integer.parseInt(rgPriorityValue.getText().toString()),
                    etDueDate.getText().toString(), false, etNotes.getText().toString(),
                    LocalDateTime.now().toString(), etDueTime.getText().toString());
            modifiedTask.setId(todoTask.getId());
            return modifiedTask;
        }
    }

    public void setOnTaskModifiedListener(OnTaskModifiedListener listener) {
        this.onTaskModifiedListener = listener;
    }

    private void toast_Prohibited_Style(String message) {
        View customView = LayoutInflater.from(getContext()).inflate(R.layout.custom_toast_prohibited_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(getContext());
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 40); // 设置在屏幕顶部
        toast.show();
    }

    private void showTimePickerDialog() {
        // 获取当前时间
        Calendar calendar = Calendar.getInstance();
        int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
        int currentMinute = calendar.get(Calendar.MINUTE);

        // 创建 TimePickerDialog
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                getContext(),
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        // 处理用户选择的时间
                        String selectedTime = String.format("%02d:%02d", hourOfDay, minute);
                        etDueTime.setText(selectedTime);
                    }
                },
                currentHour, // 当前小时
                currentMinute, // 当前分钟
                true // 使用 24 小时制
        );

        // 显示时间选择器
        timePickerDialog.show();
    }

    public boolean isValidDate(String input) {
        String datePattern = "^\\d{4}-\\d{2}-\\d{2}$";
        return input.matches(datePattern);
    }

    public boolean isValidTime(String input) {
        String timePattern = "^\\d{2}:\\d{2}$";
        return input.matches(timePattern);
    }

    public void showToastAboveView(View view, Context context, String message) {
        // 创建Toast
        View customView = LayoutInflater.from(context).inflate(R.layout.custom_toast_confirm_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(context);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 获取控件的位置（相对于屏幕）
        int[] location = new int[2];
        view.getLocationOnScreen(location); // 获取控件在屏幕上的位置
        int viewX = location[0]; // 控件的X坐标
        int viewY = location[1]; // 控件的Y坐标

        WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = 0;
        if (insets != null) {
            cutoutHeight = insets.getSystemWindowInsetTop(); // 获取刘海高度
        }

        // 计算Toast的偏移量
        int xOffset = 0; // 水平偏移量，与控件的X坐标对齐
        int yOffset = viewY - cutoutHeight; // 垂直偏移量，让Toast显示在控件的顶部

        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, xOffset, yOffset);

        // 显示Toast
        toast.show();
    }
}
